package com.chengcang.api.modules.busi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.chengcang.api.modules.busi.dao.BusiAddressDao;
import com.chengcang.api.modules.busi.dto.BusiAddressDTO;
import com.chengcang.api.modules.busi.dto.BusiAddressPageDTO;
import com.chengcang.api.modules.busi.entity.BusiAddressEntity;
import com.chengcang.api.modules.busi.service.BusiAddressService;
import com.chengcang.api.modules.busi.vo.BusiAddressVo;
import com.chengcang.api.modules.login.utils.UserHolder;
import com.chengcang.common.exception.CustomException;
import com.chengcang.common.page.PageData;
import com.chengcang.common.service.impl.CrudServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 地区表
 *
 * @author zhanli
 * @since 1.0.0 2023-01-10
 */
@Service
public class BusiAddressServiceImpl extends CrudServiceImpl<BusiAddressDao, BusiAddressEntity, BusiAddressDTO> implements BusiAddressService {

    @Autowired
    private BusiAddressDao busiAddressDao;

    @Override
    public QueryWrapper<BusiAddressEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<BusiAddressEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public PageData<BusiAddressVo> page(BusiAddressPageDTO busiAddressDTO) {
        busiAddressDTO.setTenantId(UserHolder.getUser().getDefaultTenantId());
        return new PageData<BusiAddressVo>(busiAddressDao.list(busiAddressDTO), busiAddressDao.count(busiAddressDTO));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefault(String id) {
        updateDefault();
        //设置默认地址
        Long tenantId = UserHolder.getUser().getDefaultTenantId();
        busiAddressDao.update(BusiAddressEntity.builder().defaulted(0).build(), new LambdaQueryWrapper<BusiAddressEntity>()
                .eq(BusiAddressEntity::getTenantId, tenantId).eq(BusiAddressEntity::getId, id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAddr(BusiAddressDTO dto) {
        dto.setTenantId(UserHolder.getUser().getDefaultTenantId());
        if (dto.getDefaulted() == 0) {
            updateDefault();
            dto.setAddrNo(IdWorker.getIdStr());
        }
        save(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modify(BusiAddressDTO dto) {
        BusiAddressDTO busiAddressDTO = get(dto.getId());
        if (busiAddressDTO.getDefaulted() == 0 && dto.getDefaulted() == 1) {
            throw new CustomException("默认地址不允许设置成非默认地址！");
        }
        if (dto.getDefaulted() == 0) {
            updateDefault();
            dto.setAddrNo(IdWorker.getIdStr());
        }

        update(dto);
    }

    private void updateDefault() {
        Long tenantId = UserHolder.getUser().getDefaultTenantId();
        //取消原有默认地址, 0是， 1:否; TODO 不符合01语义，根据数据库备注延续使用的。
        busiAddressDao.update(BusiAddressEntity.builder().defaulted(1).build(),
                new LambdaQueryWrapper<BusiAddressEntity>()
                        .eq(BusiAddressEntity::getTenantId, tenantId)
                        .eq(BusiAddressEntity::getDefaulted, 0));
    }

    @Override
    public void delete(Long[] ids) {
        List<BusiAddressEntity> busiAddressEntities = baseDao.selectBatchIds(Arrays.asList(ids));
        if (busiAddressEntities.stream().map(BusiAddressEntity::getDefaulted).anyMatch(o -> o == 0)) {
            throw new CustomException("默认地址不允许删除");
        }
        super.delete(ids);
    }
}